package com.hp.gxw.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hp.gxw.constant.LayTableR;
import com.hp.gxw.constant.TypeEnum;
import com.hp.gxw.entity.*;
import com.hp.gxw.service.*;
import com.hp.gxw.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/manage/settlement_report")
public class SettlementReportController {

    @Autowired
    private ISaleOrderService iSaleOrderService;

    @Autowired
    private ISaleOrderDetailsService iSaleOrderDetailsService;

    @Autowired
    private ISaleOrderProcessService iSaleOrderProcessService;

    @Autowired
    private ISettlementOrderService iSettlementOrderService;

    @Autowired
    private ISettlementOrderDetailsService iSettlementOrderDetailsService;

    @Autowired
    private ISettlementOrderProcessService iSettlementOrderProcessService;

    @Autowired
    private ICustomerService iCustomerService;

    @Autowired
    private IProcessPriceOrderService iProcessPriceOrderService;

    @Autowired
    private IProductService iProductService;

    @Autowired
    private IProcessPriceProduceService iProcessPriceProduceService;

    @RequestMapping("/index")
    public String index(Model model){
        model.addAttribute("customer", iCustomerService.list());
        return "report/settlement_report/index";
    }

    @RequestMapping("/list")
    @ResponseBody
    public LayTableR list(Integer page, Integer limit, String master) throws Exception {
        QueryWrapper<SaleOrder> ew = ConditionUtil.convert(master, new QueryWrapper<>());
        Page<Map<String,Object>> pageList = iSettlementOrderService.getSettlementReportPage(new Page<>(page, limit), ew);
        for (Map<String, Object> record : pageList.getRecords()) {
            if(record.get("settlement_type").equals(TypeEnum.exception_settlement.getCode())){
                if(record.get("pricing_method").equals("计时")){
                    record.put("amountinfo","结算单价*实际工时*结算数量="+new BigDecimal(record.get("settlementcost").toString()).multiply(new BigDecimal(record.get("act_hours").toString())).multiply(new BigDecimal(record.get("settlement_qty").toString())).setScale(2));
                }
                else{
                    record.put("amountinfo","结算单价*结算数量="+new BigDecimal(record.get("settlementcost").toString()).multiply(new BigDecimal(record.get("settlement_qty").toString())).setScale(2));
                }
            }else{
                if(record.get("pricing_method").equals("计时")){
                    record.put("amountinfo","结算单价*标准工时*结算数量="+new BigDecimal(record.get("settlementcost").toString()).multiply(new BigDecimal(record.get("expect_hours").toString())).multiply(new BigDecimal(record.get("settlement_qty").toString())).setScale(2));
                }
                else{
                    record.put("amountinfo","结算单价*结算数量="+new BigDecimal(record.get("settlementcost").toString()).multiply(new BigDecimal(record.get("settlement_qty").toString())).setScale(2));
                }
            }
        }
        return LayTableR.result(0, pageList.getTotal(), pageList.getRecords());
    }

    @RequestMapping("/download")
    @ResponseBody
    public void download(String condition, HttpServletResponse response) {
        List<Map> conditionList = JSON.parseArray(condition, Map.class);
        try {
            String queryCriteriaStr = "【查询条件】";
            QueryWrapper qw = new QueryWrapper();
            if(conditionList.size() > 0){
                for(Map m : conditionList){
                    queryCriteriaStr = queryCriteriaStr+m.get("title")+": "+m.get("value")+";   ";
                    switch (m.get("type").toString()){
                        case "equal":
                            qw.eq(m.get("field").toString(), m.get("value"));
                            break;
                        case "like":
                            qw.like(m.get("field").toString(), m.get("value"));
                            break;
                        case "unequal":
                            qw.ne(m.get("field").toString(), m.get("value"));
                            break;
                        case "empty":
                            qw.isNull(m.get("field").toString());
                            break;
                        case "notempty":
                            qw.isNotNull(m.get("field").toString());
                            break;
                        case "between":
                            qw.between(m.get("field").toString(), m.get("left"), m.get("right"));
                            break;
                        case "greater_than":
                            qw.gt(m.get("field").toString(), m.get("value"));
                            break;
                        case "less_than":
                            qw.lt(m.get("field").toString(), m.get("value"));
                            break;
                        case "start":
                            qw.likeLeft(m.get("field").toString(), m.get("value"));
                            break;
                        case "end":
                            qw.likeRight(m.get("field").toString(), m.get("value"));
                            break;
                    }
                }
            }else{
                queryCriteriaStr = queryCriteriaStr+"无查询条件，查询全表";
            }
            //excel表头
            List<TitleEntity> titleList=new ArrayList<>();
            titleList.add(new TitleEntity("0",null,"销售订单报表",null));
            titleList.add(new TitleEntity("1","0",queryCriteriaStr,null));
            titleList.add(new TitleEntity("2","1","结算单号","order_no"));
            titleList.add(new TitleEntity("3","1","结算状态","settlement_type"));
            titleList.add(new TitleEntity("4","1","销售订单号","sale_order_no"));
            titleList.add(new TitleEntity("5","1","客户编码","customer_code"));
            titleList.add(new TitleEntity("6","1","客户名称","customer_name"));
            titleList.add(new TitleEntity("7","1","客户订单号","customer_order"));
            titleList.add(new TitleEntity("8","1","关联订单号","related_order"));
            titleList.add(new TitleEntity("9","1","业务员","person_name"));
            titleList.add(new TitleEntity("10","1","订单创建时间","create_time"));
            titleList.add(new TitleEntity("11","1","产品编码","cinvcode"));
            titleList.add(new TitleEntity("12","1","产品名称","cinvname"));
            titleList.add(new TitleEntity("13","1","类型","type"));
            titleList.add(new TitleEntity("14","1","批号","cbatch"));
            titleList.add(new TitleEntity("15","1","订单数量","qty"));
            titleList.add(new TitleEntity("16","1","累计结算数量","total_settlement_qty"));
            titleList.add(new TitleEntity("17","1","累计结算金额","total_settlement_amount"));
            titleList.add(new TitleEntity("18","1","结算数量","settlement_qty"));
            titleList.add(new TitleEntity("19","1","结算金额","settlement_amount"));
            titleList.add(new TitleEntity("20","1","工序序列号","serial_number"));
//            titleList.add(new TitleEntity("21","1","加工工序编码","product_process"));
//            titleList.add(new TitleEntity("22","1","加工工序名称","product_process_name"));
            titleList.add(new TitleEntity("23","1","订单工序编码","order_process"));
            titleList.add(new TitleEntity("24","1","订单工序名称","order_process_name"));
            titleList.add(new TitleEntity("25","1","计价方式","pricing_method"));
            titleList.add(new TitleEntity("26","1","标准工时","expect_hours"));
            titleList.add(new TitleEntity("27","1","实际工时","act_hours"));
            titleList.add(new TitleEntity("28","1","订单单价","ioritaxcost"));
            titleList.add(new TitleEntity("29","1","结算单价","settlementcost"));
            titleList.add(new TitleEntity("30","1","金额明细","amountinfo"));
            //excel数据
            List<Map<String,Object>> list = iSettlementOrderService.getSettlementReportList(qw);
            for (Map<String, Object> record : list) {
                if(record.get("settlement_type").equals(TypeEnum.exception_settlement.getCode())){
                    if(record.get("pricing_method").equals("计时")){
                        record.put("amountinfo","结算单价*实际工时*结算数量="+new BigDecimal(record.get("settlementcost").toString()).multiply(new BigDecimal(record.get("act_hours").toString())).multiply(new BigDecimal(record.get("settlement_qty").toString())).setScale(2));
                    }
                    else{
                        record.put("amountinfo","结算单价*结算数量="+new BigDecimal(record.get("settlementcost").toString()).multiply(new BigDecimal(record.get("settlement_qty").toString())).setScale(2));
                    }
                }else{
                    if(record.get("pricing_method").equals("计时")){
                        record.put("amountinfo","结算单价*标准工时*结算数量="+new BigDecimal(record.get("settlementcost").toString()).multiply(new BigDecimal(record.get("expect_hours").toString())).multiply(new BigDecimal(record.get("settlement_qty").toString())).setScale(2));
                    }
                    else{
                        record.put("amountinfo","结算单价*结算数量="+new BigDecimal(record.get("settlementcost").toString()).multiply(new BigDecimal(record.get("settlement_qty").toString())).setScale(2));
                    }
                }
                record.put("settlement_type",record.get("settlement_type").equals(TypeEnum.exception_settlement.getCode())?TypeEnum.normal_settlement.getDescribe():TypeEnum.exception_settlement.getDescribe());
            }
            ExcelTool excelTool = new ExcelTool("销售订单报表",20,20);
            List<Column>  titleData = excelTool.columnTransformer(titleList,"t_id","t_pid","t_content","t_fielName","0");
            response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode("销售订单报表"+ DateUtil.currentYYMMDD()+".xlsx", "utf-8"));
            excelTool.exportExcel(titleData,list, response.getOutputStream(),true,true);
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/process_info")
    @ResponseBody
    public LayTableR process_info(String detailId) throws Exception {
        SaleOrderDetails saleOrderDetails = iSaleOrderDetailsService.getOne(new LambdaQueryWrapper<SaleOrderDetails>().eq(SaleOrderDetails::getMesId, detailId));
        SaleOrder saleOrder = iSaleOrderService.getById(saleOrderDetails.getMasterId());
        List<SaleOrderProcess> processList = iSaleOrderProcessService.list(new LambdaQueryWrapper<SaleOrderProcess>()
                .eq(SaleOrderProcess::getDetailsId, saleOrderDetails.getId()).orderByAsc(SaleOrderProcess::getSerialNumber));
        Customer customer = iCustomerService.getOne(new LambdaQueryWrapper<Customer>().eq(Customer::getCode, saleOrder.getCustomerCode()));
        Product product = iProductService.getOne(new LambdaQueryWrapper<Product>().eq(Product::getCode, saleOrderDetails.getCinvcode()));
        SettlementOrder settlementOrder = iSettlementOrderService.getOne(new LambdaQueryWrapper<SettlementOrder>().eq(SettlementOrder::getSaleOrderNo, saleOrder.getOrderNo()));
//        SettlementOrderDetails settlementOrderDetails = iSettlementOrderDetailsService.getOne(new LambdaQueryWrapper<SettlementOrderDetails>().eq(SettlementOrderDetails::getMasterId, settlementOrder.getId())
//                .eq(SettlementOrderDetails::getDetailId, saleOrderDetails.getMesId()));
//        List<SettlementOrderProcess> settlementList = iSettlementOrderProcessService.list(new LambdaQueryWrapper<SettlementOrderProcess>()
//                .eq(SettlementOrderProcess::getDetailsId, settlementOrderDetails.getId())
//                .orderByAsc(SettlementOrderProcess::getSerialNumber));
        for (SaleOrderProcess saleOrderProcess : processList){
            saleOrderProcess.setQty(saleOrderDetails.getQty());
            ProcessPriceOrder priceOrder = iProcessPriceOrderService.getOne(new LambdaQueryWrapper<ProcessPriceOrder>()
                    .eq(ProcessPriceOrder::getCustomerId, customer.getId())
                    .eq(ProcessPriceOrder::getProductId, product.getId())
                    .eq(ProcessPriceOrder::getType, saleOrderDetails.getType())
                    .eq(ProcessPriceOrder::getOrderProcessCode, saleOrderProcess.getOrderProcess()));
//            saleOrderProcess.setPricingMethod(priceOrder.getPricingMethod());
            saleOrderProcess.setExpectHours(priceOrder.getExpectHours());
//            saleOrderProcess.setSettlementType(settlementOrderDetails.getSettlementType());
//            List<ProcessPriceProduce> produceList = iProcessPriceProduceService.list(new LambdaQueryWrapper<ProcessPriceProduce>()
//                    .eq(ProcessPriceProduce::getOrderId, priceOrder.getId()));
//            Set<String> set = produceList.stream().map(ProcessPriceProduce::getProduceProcessCode).collect(Collectors.toSet());
//            List<SettlementOrderProcess> settlementOrderProcessList = iSettlementOrderProcessService.list(new LambdaQueryWrapper<SettlementOrderProcess>()
//                    .eq(SettlementOrderProcess::getDetailsId, settlementOrderDetails.getId())
//                    .in(SettlementOrderProcess::getProductProcess, set).orderByAsc(SettlementOrderProcess::getSerialNumber));
//            if(settlementOrderProcessList.size() > 0){
//                saleOrderProcess.setSettlementQty(settlementList.get(0).getQty());
//                saleOrderProcess.setActHours(settlementOrderProcessList.stream().map(SettlementOrderProcess::getExpectHours).reduce(BigDecimal.ZERO,BigDecimal::add));
//                if(settlementOrderDetails.getSettlementType().equals(TypeEnum.exception_settlement.getCode())){
//                    if(priceOrder.getPricingMethod().equals("计时")){
//                        saleOrderProcess.setSettlementAmountInfo("结算单价*实际工时*结算数量="+saleOrderProcess.getSettlementcost().multiply(saleOrderProcess.getActHours()).multiply(saleOrderProcess.getSettlementQty()).setScale(2));
//                    }
//                    else{
//                        saleOrderProcess.setSettlementAmountInfo("结算单价*结算数量="+saleOrderProcess.getSettlementcost().multiply(saleOrderProcess.getSettlementQty()).setScale(2));
//                    }
//                }else{
//                    if(priceOrder.getPricingMethod().equals("计时")){
//                        saleOrderProcess.setSettlementAmountInfo("结算单价*标准工时*结算数量="+saleOrderProcess.getSettlementcost().multiply(priceOrder.getExpectHours()).multiply(saleOrderProcess.getSettlementQty()).setScale(2));
//                    }
//                    else{
//                        saleOrderProcess.setSettlementAmountInfo("结算单价*结算数量="+saleOrderProcess.getSettlementcost().multiply(saleOrderProcess.getSettlementQty()).setScale(2));
//                    }
//                }
//            }
        }
        return LayTableR.result(0, processList.size(), processList);
    }

    @RequestMapping("/product_process_info")
    @ResponseBody
    public LayTableR product_process_info(String processId) throws Exception {
        SaleOrderProcess saleOrderProcess = iSaleOrderProcessService.getById(processId);
        SaleOrderDetails saleOrderDetails = iSaleOrderDetailsService.getOne(new LambdaQueryWrapper<SaleOrderDetails>().eq(SaleOrderDetails::getMesId, saleOrderProcess.getDetailsId()));
        SaleOrder saleOrder = iSaleOrderService.getById(saleOrderDetails.getMasterId());
        Customer customer = iCustomerService.getOne(new LambdaQueryWrapper<Customer>().eq(Customer::getCode, saleOrder.getCustomerCode()));
        Product product = iProductService.getOne(new LambdaQueryWrapper<Product>().eq(Product::getCode, saleOrderDetails.getCinvcode()));
        SettlementOrder settlementOrder = iSettlementOrderService.getOne(new LambdaQueryWrapper<SettlementOrder>().eq(SettlementOrder::getSaleOrderNo, saleOrder.getOrderNo()));
        SettlementOrderDetails settlementOrderDetails = iSettlementOrderDetailsService.getOne(new LambdaQueryWrapper<SettlementOrderDetails>().eq(SettlementOrderDetails::getMasterId, settlementOrder.getId())
                .eq(SettlementOrderDetails::getDetailId, saleOrderDetails.getMesId()));
        ProcessPriceOrder priceOrder = iProcessPriceOrderService.getOne(new LambdaQueryWrapper<ProcessPriceOrder>()
                .eq(ProcessPriceOrder::getCustomerId, customer.getId())
                .eq(ProcessPriceOrder::getProductId, product.getId())
                .eq(ProcessPriceOrder::getType, saleOrderDetails.getType())
                .eq(ProcessPriceOrder::getOrderProcessCode, saleOrderProcess.getOrderProcess()));
        List<ProcessPriceProduce> produceList = iProcessPriceProduceService.list(new LambdaQueryWrapper<ProcessPriceProduce>()
                .eq(ProcessPriceProduce::getOrderId, priceOrder.getId()));
        Set<String> set = produceList.stream().map(ProcessPriceProduce::getProduceProcessCode).collect(Collectors.toSet());
        List<SettlementOrderProcess> settlementOrderProcessList = iSettlementOrderProcessService.list(new LambdaQueryWrapper<SettlementOrderProcess>()
                .eq(SettlementOrderProcess::getDetailsId, settlementOrderDetails.getId())
                .in(SettlementOrderProcess::getProductProcess, set).orderByAsc(SettlementOrderProcess::getSerialNumber));
        if(settlementOrderProcessList.size() < 1){
            return LayTableR.result(0, settlementOrderProcessList.size(), settlementOrderProcessList);
        }
        List<SettlementOrderProcess> settlementList = iSettlementOrderProcessService.list(new LambdaQueryWrapper<SettlementOrderProcess>()
                .eq(SettlementOrderProcess::getDetailsId, settlementOrderDetails.getId())
                .orderByAsc(SettlementOrderProcess::getSerialNumber));
//        settlementOrderProcessList.get(0).setSettlementAmount("结算单价*结算数量="+saleOrderProcess.getSettlementcost().multiply(settlementList.get(0).getQty()).setScale(2));
//        for(SettlementOrderProcess settlementOrderProcess : settlementOrderProcessList){
//            settlementOrderProcess.setSettlementType(settlementOrderDetails.getSettlementType());
//            settlementOrderProcess.setPricingMethod(priceOrder.getPricingMethod());
//            settlementOrderProcess.setSettlementQty(settlementList.get(0).getQty());
//            settlementOrderProcess.setSettlementCost(saleOrderProcess.getSettlementcost());
//            if(settlementOrderDetails.getSettlementType().equals(TypeEnum.exception_settlement.getCode())){
//                if(priceOrder.getPricingMethod().equals("计时")){
//                    settlementOrderProcess.setSettlementAmount("结算单价*实际工时*结算数量="+settlementOrderProcess.getSettlementCost().multiply(settlementOrderProcess.getExpectHours()).multiply(settlementOrderProcess.getSettlementQty()).setScale(2));
//                }
////                else{
////                    settlementOrderProcess.setSettlementAmount("结算单价*结算数量="+settlementOrderProcess.getSettlementCost().multiply(settlementOrderProcess.getSettlementQty()).setScale(2));
////                }
//            }else{
//                if(priceOrder.getPricingMethod().equals("计时")){
//                    settlementOrderProcess.setSettlementAmount("结算单价*标准工时*结算数量="+settlementOrderProcess.getSettlementCost().multiply(priceOrder.getExpectHours()).multiply(settlementOrderProcess.getSettlementQty()).setScale(2));
//                }
////                else{
////                    settlementOrderProcess.setSettlementAmount("结算单价*结算数量="+settlementOrderProcess.getSettlementCost().multiply(settlementOrderProcess.getSettlementQty()).setScale(2));
////                }
//            }
//        }
        return LayTableR.result(0, settlementOrderProcessList.size(), settlementOrderProcessList);
    }
}
